// 学习页面逻辑
Page({
  // 在Page({}) 中添加加载状态
  data: {
    isLoading: true,
    // 当前学习进度
    currentIndex: 0,
    totalWords: 20,
    progressPercent: 0,
    
    // 答案相关状态
    showAnswer: false,
    isCorrect: false,
    hasSelection: false,
    
    // 当前选择的词书ID
    currentWordbookId: 2,
    
    // 选项数据
    options: [],
    
    // 示例单词数据
    words: [],
    currentWord: null,
    reviewWords: [], // 复习单词列表
    selectedOptionIndex: -1, // 选中的选项索引
  },

  // 音频上下文对象
  audioContext: null,

  onLoad() {
    // 获取全局数据中的词书选择
    const app = getApp();
    if (app.globalData.currentWordbook) {
      this.setData({
        currentWordbookId: app.globalData.currentWordbook.id
      });
    }
    
    // 初始化音频上下文
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onError((res) => {
      console.error('音频播放错误:', res);
      wx.showToast({
        title: '音频加载失败',
        icon: 'none'
      });
    });
    
    // 预加载单词数据
    this.preloadWords();
  },
  
  onUnload() {
    // 页面卸载时释放音频资源
    if (this.audioContext) {
      this.audioContext.stop();
      this.audioContext.destroy();
    }
  },
  
  // 预加载单词数据
  preloadWords: function() {
    this.setData({ isLoading: true });
    
    // 从本地存储中获取需要复习的单词
    const reviewWordsKey = `reviewWords_${this.data.currentWordbookId}`;
    try {
      const reviewWords = wx.getStorageSync(reviewWordsKey) || [];
      this.setData({ reviewWords });
    } catch (e) {
      console.error('获取复习单词失败', e);
    }
    
    // 模拟API调用，获取示例单词数据
    setTimeout(() => {
      const exampleWords = this.getExampleWords();
      this.setData({ 
        words: exampleWords,
        isLoading: false
      });
      
      // 加载当前单词
      this.loadCurrentWord();
    }, 1000);
  },
  
  // 加载当前单词，优先加载复习单词
  loadCurrentWord: function() {
    const { currentIndex, words, reviewWords } = this.data;
    
    // 如果当前没有单词或索引超出范围，结束学习
    if (!words.length || currentIndex >= words.length) {
      wx.showToast({
        title: '学习完成',
        icon: 'success',
        duration: 2000
      });
      
      // 保存学习进度
      this.saveProgress();
      
      // 返回首页
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
      return;
    }
    
    const currentWord = words[currentIndex];
    
    // 更新进度条
    const progressPercent = ((currentIndex + 1) / this.data.totalWords) * 100;
    
    // 生成选项
    const options = this.generateOptions(currentWord);
    
    this.setData({
      currentWord,
      progressPercent,
      options,
      selectedOptionIndex: -1,
      hasSelection: false,
      showAnswer: false,
      isCorrect: false
    });
  },
  
  // 生成选项，包括正确答案和干扰选项
  generateOptions: function(word) {
    // 确保当前单词的翻译作为正确选项
    let options = [word.translation];
    
    // 从所有单词中随机选择两个不同的单词作为干扰选项
    const otherWords = this.data.words.filter(w => w.word !== word.word);
    
    // 如果单词不足，使用默认选项
    if (otherWords.length < 2) {
      options.push('熟悉的人或事物', '突然明白；领悟');
    } else {
      // 随机选择两个不同的单词
      const shuffled = this.shuffleArray([...otherWords]);
      options.push(shuffled[0].translation, shuffled[1].translation);
    }
    
    // 打乱选项顺序
    return this.shuffleArray(options);
  },
  
  // 选择选项
  selectOption: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedOptionIndex: index,
      hasSelection: true
    });
  },
  
  // 确认选择
  confirmSelection: function() {
    if (!this.data.hasSelection) return;
    
    const { selectedOptionIndex, options, currentWord } = this.data;
    const selectedOption = options[selectedOptionIndex];
    const isCorrect = selectedOption === currentWord.translation;
    
    // 如果回答错误，将当前单词添加到复习列表
    if (!isCorrect) {
      this.addToReviewList(currentWord);
    }
    
    this.setData({
      showAnswer: true,
      isCorrect
    });
  },
  
  // 添加到复习列表
  addToReviewList: function(word) {
    const { reviewWords, currentWordbookId } = this.data;
    
    // 检查是否已在复习列表中
    const isExist = reviewWords.some(item => item.word === word.word);
    if (!isExist) {
      const updatedReviewWords = [...reviewWords, word];
      
      // 更新本地数据
      this.setData({ reviewWords: updatedReviewWords });
      
      // 保存到本地存储
      const reviewWordsKey = `reviewWords_${currentWordbookId}`;
      try {
        wx.setStorageSync(reviewWordsKey, updatedReviewWords);
      } catch (e) {
        console.error('保存复习单词失败', e);
      }
    }
  },
  
  // 进入下一个单词
  nextWord: function() {
    const newIndex = this.data.currentIndex + 1;
    this.setData({
      currentIndex: newIndex
    }, () => {
      this.loadCurrentWord();
    });
  },
  
  // 保存学习进度
  saveProgress: function() {
    try {
      // 获取当前日期
      const today = new Date().toISOString().split('T')[0];
      
      // 从本地存储获取学习记录
      const studyRecord = wx.getStorageSync('studyRecord') || {};
      
      // 更新今日学习记录
      const todayRecord = studyRecord[today] || { newWords: 0, reviewWords: 0 };
      todayRecord.newWords += this.data.words.length - this.data.reviewWords.length;
      
      // 更新记录
      studyRecord[today] = todayRecord;
      
      // 保存回本地存储
      wx.setStorageSync('studyRecord', studyRecord);
      
      // 更新全局数据
      const app = getApp();
      if (app.globalData.studyData) {
        app.globalData.studyData.totalWords += this.data.words.length;
        app.globalData.studyData.todayWords = todayRecord.newWords;
      }
      
      // 更新首页显示
      this.updateHomePageData();
    } catch (e) {
      console.error('保存学习进度失败', e);
    }
  },
  
  // 更新首页数据
  updateHomePageData: function() {
    const app = getApp();
    if (!app.globalData) return;
    
    // 获取今日学习目标
    const dailyGoal = 50; // 默认每日50词
    const todayWords = app.globalData.studyData?.todayWords || 0;
    const reviewWords = this.data.reviewWords.length;
    
    // 更新本地存储中的数据
    try {
      wx.setStorageSync('dailyProgress', {
        todayWords,
        dailyGoal,
        reviewWords
      });
    } catch (e) {
      console.error('更新首页数据失败', e);
    }
  },
  
  // 播放单词读音
  playSound: function() {
    const { currentWord } = this.data;
    if (!currentWord) return;
    
    // 停止当前正在播放的音频
    this.audioContext.stop();
    
    // 获取发音URL
    const word = currentWord.word.toLowerCase();
    
    // 使用有道词典API获取发音
    // 美式发音：http://dict.youdao.com/dictvoice?audio=单词&type=2
    // 英式发音：http://dict.youdao.com/dictvoice?audio=单词&type=1
    const audioUrl = `https://dict.youdao.com/dictvoice?audio=${word}&type=2`;
    
    // 设置音频源并播放
    this.audioContext.src = audioUrl;
    this.audioContext.play();
    
    // 显示提示
    wx.vibrateShort({
      type: 'light'
    });
  },
  
  // 播放例句发音
  playExampleSound: function() {
    // 获取当前例句内容
    const { currentWord } = this.data;
    if (!currentWord || !currentWord.example) return;
    
    // 停止当前正在播放的音频
    this.audioContext.stop();
    
    // 将例句分割为单词并取前6个词（避免句子太长无法播放）
    const exampleWords = currentWord.example.split(' ').slice(0, 6).join(' ');
    const sentence = encodeURIComponent(exampleWords);
    
    // 使用有道词典API播放例句
    const audioUrl = `https://dict.youdao.com/dictvoice?audio=${sentence}&type=2`;
    
    // 设置音频源并播放
    this.audioContext.src = audioUrl;
    this.audioContext.play();
    
    // 显示提示并震动
    wx.vibrateShort({
      type: 'light'
    });
    
    wx.showToast({
      title: '正在播放例句',
      icon: 'none',
      duration: 1500
    });
  },
  
  // 数组随机排序函数
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },
  
  // 获取示例单词数据
  getExampleWords: function() {
    // 根据不同词书返回不同的示例单词
    let wordList = [];
    
    // 初二英语词汇示例
    if (this.data.currentWordbookId === 2) {
      wordList = [
        {
          word: "abandon",
          type: "v.",
          phonetic: "əˈbændən",
          translation: "放弃；抛弃",
          example: "He decided to abandon the project because it was too difficult.",
          exampleTranslation: "他决定放弃这个项目，因为它太困难了。"
        },
        {
          word: "ability",
          type: "n.",
          phonetic: "əˈbɪləti",
          translation: "能力；才能",
          example: "She has the ability to solve complex problems.",
          exampleTranslation: "她有解决复杂问题的能力。"
        },
        {
          word: "abroad",
          type: "adv.",
          phonetic: "əˈbrɔːd",
          translation: "在国外；到国外",
          example: "He is currently studying abroad in France.",
          exampleTranslation: "他目前在法国留学。"
        },
        {
          word: "absence",
          type: "n.",
          phonetic: "ˈæbsəns",
          translation: "缺席；不在场",
          example: "Her absence was noted at the meeting.",
          exampleTranslation: "她的缺席在会议上被注意到了。"
        },
        {
          word: "accept",
          type: "v.",
          phonetic: "əkˈsept",
          translation: "接受；同意",
          example: "I accept your apology.",
          exampleTranslation: "我接受你的道歉。"
        },
        {
          word: "accident",
          type: "n.",
          phonetic: "ˈæksɪdənt",
          translation: "事故；意外",
          example: "He was involved in a car accident last week.",
          exampleTranslation: "他上周卷入了一场车祸。"
        },
        {
          word: "accommodation",
          type: "n.",
          phonetic: "əˌkɒməˈdeɪʃn",
          translation: "住宿；住处",
          example: "The hotel provides comfortable accommodation for all guests.",
          exampleTranslation: "这家酒店为所有客人提供舒适的住宿。"
        },
        {
          word: "accompany",
          type: "v.",
          phonetic: "əˈkʌmpəni",
          translation: "陪伴；伴随",
          example: "She offered to accompany me to the doctor.",
          exampleTranslation: "她主动提出陪我去看医生。"
        },
        {
          word: "achieve",
          type: "v.",
          phonetic: "əˈtʃiːv",
          translation: "实现；达到",
          example: "She worked hard to achieve her goals.",
          exampleTranslation: "她努力工作以实现自己的目标。"
        },
        {
          word: "acknowledge",
          type: "v.",
          phonetic: "əkˈnɒlɪdʒ",
          translation: "承认；确认",
          example: "He acknowledged that he had made a mistake.",
          exampleTranslation: "他承认自己犯了个错误。"
        },
        {
          word: "acquire",
          type: "v.",
          phonetic: "əˈkwaɪə(r)",
          translation: "获得；取得",
          example: "She acquired a taste for coffee when she was in college.",
          exampleTranslation: "她在大学时期养成了喝咖啡的习惯。"
        },
        {
          word: "activity",
          type: "n.",
          phonetic: "ækˈtɪvəti",
          translation: "活动；行动",
          example: "The school offers many after-school activities.",
          exampleTranslation: "学校提供许多课后活动。"
        },
        {
          word: "adapt",
          type: "v.",
          phonetic: "əˈdæpt",
          translation: "适应；调整",
          example: "It took him a while to adapt to his new surroundings.",
          exampleTranslation: "他花了一段时间来适应新环境。"
        },
        {
          word: "addition",
          type: "n.",
          phonetic: "əˈdɪʃn",
          translation: "添加；加法",
          example: "In addition to English, he also speaks French and Spanish.",
          exampleTranslation: "除了英语，他还说法语和西班牙语。"
        },
        {
          word: "address",
          type: "n./v.",
          phonetic: "əˈdres",
          translation: "地址；演讲；处理",
          example: "Please write your name and address on this form.",
          exampleTranslation: "请在此表格上写下您的姓名和地址。"
        },
        {
          word: "adequate",
          type: "adj.",
          phonetic: "ˈædɪkwət",
          translation: "足够的；适当的",
          example: "The food supplies were adequate for a week.",
          exampleTranslation: "食物供应足够维持一周。"
        },
        {
          word: "adjust",
          type: "v.",
          phonetic: "əˈdʒʌst",
          translation: "调整；适应",
          example: "You need to adjust the settings on your camera.",
          exampleTranslation: "你需要调整相机上的设置。"
        },
        {
          word: "admire",
          type: "v.",
          phonetic: "ədˈmaɪə(r)",
          translation: "钦佩；赞赏",
          example: "I admire your courage and determination.",
          exampleTranslation: "我钦佩你的勇气和决心。"
        },
        {
          word: "admission",
          type: "n.",
          phonetic: "ədˈmɪʃn",
          translation: "入场费；承认；录取",
          example: "The admission fee for the museum is $10.",
          exampleTranslation: "博物馆的入场费是10美元。"
        },
        {
          word: "adopt",
          type: "v.",
          phonetic: "əˈdɒpt",
          translation: "收养；采纳",
          example: "They decided to adopt a child from China.",
          exampleTranslation: "他们决定从中国收养一个孩子。"
        }
      ];
    } else if (this.data.currentWordbookId === 1) {
      // 初一英语词汇示例
      wordList = [
        {
          word: "apple",
          type: "n.",
          phonetic: "ˈæpl",
          translation: "苹果",
          example: "I eat an apple every day.",
          exampleTranslation: "我每天吃一个苹果。"
        },
        // 其他初一词汇...
      ];
    } else if (this.data.currentWordbookId === 3) {
      // 初三英语词汇示例
      wordList = [
        {
          word: "accelerate",
          type: "v.",
          phonetic: "əkˈseləreɪt",
          translation: "加速；促进",
          example: "The car accelerated quickly as it left the town.",
          exampleTranslation: "汽车离开小镇时快速加速。"
        },
        // 其他初三词汇...
      ];
    }
    
    // 如果有复习单词，优先加载
    let finalWordList = [];
    if (this.data.reviewWords.length > 0) {
      // 将复习单词放在前面
      finalWordList = [...this.data.reviewWords];
      
      // 如果复习单词不足totalWords个，补充新单词
      const remainingCount = this.data.totalWords - finalWordList.length;
      if (remainingCount > 0) {
        // 找出不在复习列表中的单词
        const newWords = wordList.filter(word => 
          !finalWordList.some(item => item.word === word.word)
        ).slice(0, remainingCount);
        
        finalWordList = [...finalWordList, ...newWords];
      }
    } else {
      // 没有复习单词时，直接使用新单词
      finalWordList = wordList.slice(0, this.data.totalWords);
    }
    
    return finalWordList;
  },
  
  // 播放单词发音
  playPronunciation: function() {
    // 已被playSound代替
    this.playSound();
  },
  
  // 播放例句发音
  playExample: function() {
    // 已被playExampleSound代替
    this.playExampleSound();
  },
});